<template>
  <div class="amap-wrapper">

    <div id="container" class="map" />
    <el-dialog
      title="提示"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
      top="40vh"
      class="dialog-footer"
    >
      <span>这是一段信息</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader'

export default {
  data() {
    return {
      map: null,
      dialogVisible: false
    }
  },
  mounted() {
    this.initAMap()
  },
  beforeDestroy() {
    if (this.map) {
      this.map.destroy()
    }
  },
  methods: {
    // 初始化高德地图
    initAMap() {
      // 设置安全密钥
      window._AMapSecurityConfig = {
        securityJsCode: '0dcc74ce5cf954879f0c66102b91b603'
      }

      AMapLoader.load({
        key: 'f5df7833011ec6480fc08ffcff8751bd',
        version: '2.0'
      })
        .then((AMap) => {
          // 创建地图实例
          this.map = new AMap.Map('container', {
            viewMode: '3D',
            zoom: 8,
            center: [119.5259671942601, 38.89472719832739],
            mapStyle: 'amap://styles/0c44903cbdb3742bb7fc9b9df69f9ded'
          })

          console.log('地图初始化成功')

          // 初始化自定义图标
          this.initIcon(AMap)
        })
        .catch((error) => {
          console.error('地图加载失败:', error)
        })
    },

    // 创建自定义icon
    initIcon(AMap) {
      const icon = new AMap.Icon({
        image: require('@/assets/images/icon.png'),
        imageSize: new AMap.Size(36, 36)
      })
      // 创建带文字的标记
      const textMarker = new AMap.Text({
        text: '浮标一号',
        position: [119.5259671942601, 38.89472719832739],
        style: {
          'padding': '5px',
          'background-color': 'transparent',
          'border': '0px solid #ccc',
          'text-align': 'center',
          'color': 'red'

        },
        offset: new AMap.Pixel(-12, 30) // 调整文字位置
      })

      const marker = new AMap.Marker({
        icon: icon,
        position: [119.5259671942601, 38.89472719832739],
        title: '浮标一号'
      })
      marker.on('click', () => {
        this.dialogVisible = true
      })
      this.map.add([marker, textMarker])
    }
  }
}
</script>

<style scoped>
.amap-wrapper {
  width: 100%;
  height: 100%;

}

#container {
  width: 100%;
  height: 100%;

}
::v-deep .el-dialog {
  margin-top: 40vh !important;
}
</style>
